# -*- coding:utf-8 -*-
import os
import sys
import requests
import datetime
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from bs4 import BeautifulSoup
# pip install beautifulsoup4  中文文档：https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/


# reload(sys)
# sys.setdefaultencoding(‘utf-8‘)

# import importlib
#
# importlib.reload(sys)


def download(url):
    # download_path = os.getcwd() + "\download"
    # if not os.path.exists(download_path):
    #     os.mkdir(download_path)
    #
    # # 新建日期文件夹
    # download_path = os.path.join(download_path, datetime.datetime.now().strftime('% Y % m % d_ % H % M % S'))
    # # print download_path
    # os.mkdir(download_path)

    download_path = "E:\mp4"

    all_content = requests.get(url).text  # 获取第一层M3U8文件内容
    if "#EXTM3U" not in all_content:
        raise BaseException("非M3U8的链接")

    if "EXT-X-STREAM-INF" in all_content:  # 第一层
        file_line = all_content.split("\n")
        for line in file_line:
            if '.m3u8' in line:
                url = url.rsplit("/", 1)[0] + "/" + line  # 拼出第二层m3u8的URL
                all_content = requests.get(url).text

    file_line = all_content.split("\n")

    unknow = True
    key = ""
    for index, line in enumerate(file_line):  # 第二层
        if "#EXT-X-KEY" in line:  # 找解密Key
            method_pos = line.find("METHOD")
            comma_pos = line.find(",")
            method = line[method_pos:comma_pos].split('=')[1]
            print("Decode Method：", method)

            uri_pos = line.find("URI")
            quotation_mark_pos = line.rfind('"')
            key_path = line[uri_pos:quotation_mark_pos].split('"')[1]

            key_url = url.rsplit("/", 1)[0] + "/" + key_path  # 拼出key解密密钥URL
            res = requests.get(key_url)
            key = res.content
            print("key：", key)

            if "EXTINF" in line:  # 找ts地址并下载
                unknow = False
            pd_url = url.rsplit("/", 1)[0] + "/" + file_line[index + 1]  # 拼出ts片段的URL
            # print pd_url

            res = requests.get(pd_url)
            c_fule_name = file_line[index + 1].rsplit("/", 1)[-1]

            if len(key):  # AES 解密
                cryptor = AES.new(key, AES.MODE_CBC, key)
                with open(os.path.join(download_path, c_fule_name + ".mp4"), 'ab') as f:
                    f.write(cryptor.decrypt(res.content))
            else:
                with open(os.path.join(download_path, c_fule_name), 'ab') as f:
                    f.write(res.content)
            f.flush()
            if unknow:
                raise BaseException("未找到对应的下载链接")
    else:
        print("下载完成")
        # merge_file(download_path)


def merge_file(path):
    os.chdir(path)
    cmd = "copy /b * new.tmp"
    os.system(cmd)
    os.system('del / Q *.ts')
    os.system('del / Q *.mp4')
    os.rename("new.tmp", "new.mp4")


def getMovie():
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                            " (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36"}

    try:
        url = "https://www.vodsee.com/search.html?searchword=" + "钢铁侠"
        r = requests.get(url, headers=header, timeout=15)
        r.raise_for_status()
        # r.status_code
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, "html.parser")
        # print(soup.prettify())  # 打印解析之后的网页内容
        # print("--------------------------------------------")

        map = {}

        for line in soup.find_all('a', "videoName"):
            name = line.string.strip().replace('\xa0','').replace('\r','').replace('\n','')
            gj = line.parent.find('span', "region").string
            lx = line.parent.find('span', "category").string
            map[name+"_"+gj+"_"+lx] = "https://www.vodsee.com" + line["href"]
        # print(soup.body.contents)
        return map
    except:
        print("爬取失败")
        return False

def getM3u8ByHtml(url):
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                            " (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36"}
    try:
        r = requests.get(url, headers=header, timeout=15)
        r.raise_for_status()
        # r.status_code
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, "html.parser")
        # print(soup.prettify())  # 打印解析之后的网页内容
        tag = soup.find(id="m3u8")
        tag = tag["value"].split("$")[1]
        return tag
    except:
        print("m3u8链接获取失败")
        return False


def getMovie2():
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                            " (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36"}

    try:
        param = {'wd': '钢铁侠'}
        url = "https://www.vodsee.com/search.html?searchword=" + "钢铁侠"
        r = requests.get(url, headers=header, params=param, timeout=15)
        r.encoding = r.apparent_encoding
        print(r.text)
        return True
    except:
        print("爬取失败")
        return False




if __name__ == '__main__':
    # url = input("please input the url of index.m3u8 file")

    getMovie()

    print(getM3u8ByHtml("https://www.vodsee.com/detail/154254.html"))

    aa = "https://2.dadi-yun.com/20190621/YPRecQxz//800kb/hls/index.m3u8"
    aa = aa[:11]+aa[11:].replace("//", "/")


    dir_path = os.path.dirname(os.path.abspath(__file__))
    dir_path2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    path = os.path.abspath(os.path.dirname(sys.argv[0]))

    f = open("E:/mp4/1/url.txt","r")
    text = f.read()
    if text:
        for i in text.split("\n"):
            if "url=" in i:
                url = i.split("url=")[1]
            elif "startnum=" in i:
                snum = i.split("startnum=")[1]
            elif "endnum=" in i:
                enum = i.split("endnum=")[1]


    urlpath = "E:/mp4/1565793277/index"
    filelist = os.listdir(urlpath)

    tslist = []
    m3u8url = ""
    for f in filelist:
        filepath = os.path.join(urlpath, f)  # 拼接路径
        if os.path.isfile(filepath):
            if os.path.splitext(f)[1] == ".txt":
                print(f)
            elif os.path.splitext(f)[1] == ".m3u8":
                m3u8url = urlpath+"/"+f
            elif os.path.splitext(f)[1] == ".ts":
                if f[:4].isalpha():  # 前4个字符是否为字母
                    tslist.append(f[-9:])
    print("--")
    # download(url)